<?php

/**
 * Class LostPasswordForm
 *
 * @author Hua Yang <htmlcook@gmail.com>
 * @package backend.models
 * @since 1.0
 */
class LostPasswordForm extends CFormModel
{
	/**
	 * @var string
	 */
	public $login;

	/**
	 * @var string
	 */
	public $verifyCode;

	/**
	 * @var User
	 */
	private $_user;

	/**
	 * @return array
	 */
	public function rules()
	{
		return array(
			array('login, verifyCode', 'required'),
			array('verifyCode', 'captcha', 'allowEmpty' => !CCaptcha::checkRequirements()),
			array('login', 'validateLogin'),
		);
	}

	/**
	 * 属性标签
	 *
	 * @see CModel::attributeLabels()
	 */
	public function attributeLabels()
	{
		return array(
			'login' => '用户名或电子邮件',
			'verifyCode' => '验证码',
		);
	}

	/**
	 * 验证账户或电子邮件
	 *
	 * @param string $attribute
	 * @param array $params
	 */
	public function validateLogin($attribute, $params)
	{
		if ($this->hasErrors()) {
			return;
		}

		$value = $this->$attribute;
		if (strpos($value, '@') !== false) {
			$label = '邮箱';
			$condition = 'email=:email';
			$params = array(':email' => $value);
		} else {
			$label = '用户名';
			$condition = 'username=:username';
			$params = array(':username' => $value);
		}

		$this->_user = User::model()->find($condition, $params);
		if (!isset($this->_user)) {
			$this->addError('login', '无效的' . $label);
		} elseif ($this->_user->status == User::STATUS_NOT_ACTIVE) {
			$this->addError('login', '邮箱未激活验证！');
		} elseif ($this->_user->status == User::STATUS_BLOCK) {
			$this->addError('login', '用户已被禁用，无法进行操作！');
		}
	}

	public function sendMail()
	{
		if (!$user = $this->getUser()) {
			return false;
		}

		try {
			$user->generateToken();
			if ($user->update('token')) {
				return Yii::app()->mail->compose('lostPassword', array('user' => $user))
					->setFrom(array('zhuanjiao.test@foxmail.com' => Yii::app()->name))
					->setTo($user->email)
					->setSubject(Yii::app()->name . '重置密码')
					->send();
			}
		} catch (Exception $e) {
			if (YII_DEBUG) {
				throw $e;
			}
			return false;
		}
	}

	/**
	 * 获取用户
	 *
	 * @return User
	 */
	public function getUser()
	{
		return $this->_user;
	}
}